package ro.fortech.workshop_demo.ui;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import ro.fortech.workshop_demo.R;
import ro.fortech.workshop_demo.data.GrandPrix;
import ro.fortech.workshop_demo.utils.Utils;

import java.util.ArrayList;

/**
 * User: florinv
 * Date: 4/16/13
 * Time: 11:10 AM
 */
public class GrandPrixListAdapter extends ArrayAdapter<GrandPrix> implements AbsListView.OnScrollListener {
    /**
     * The application context
     */
    private Context context;
    /**
     * The resource referencing the layout for the list row
     */
    private int resource;
    /**
     * List holding reference to the grand prix list from the manager
     */
    private ArrayList<GrandPrix> grandPrixList;
    /**
     * Delegate to determine row clicks
     */
    private GrandPrixListDelegate delegate;
    /**
     * The current scroll state of the grand prix list
     */
    private int scrollState;

    public GrandPrixListAdapter(Context context, int resource, ArrayList<GrandPrix> grandPrixList, GrandPrixListDelegate delegate) {
        super(context, resource, grandPrixList);
        this.context = context;
        this.resource = resource;
        this.grandPrixList = grandPrixList;
        this.delegate = delegate;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        // Check if the view has been instantiated before. If it has been created, recycle it.
        if (convertView == null) {
            holder = new ViewHolder();
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(resource, parent, false);
            holder.countryFlag = (ImageView) convertView.findViewById(R.id.grand_prix_list_row_country_flag);
            holder.raceName = (TextView) convertView.findViewById(R.id.grand_prix_list_row_race_name);
            holder.circuitName = (TextView) convertView.findViewById(R.id.grand_prix_list_row_circuit_name);
            holder.location = (TextView) convertView.findViewById(R.id.grand_prix_list_row_location);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        // Retain the current position
        holder.position = position;
        // Get the grand prix from the list corresponding to the current position
        GrandPrix grandPrix = grandPrixList.get(position);
        // Set the race name
        holder.raceName.setText(grandPrix.getRaceName());
        // Set the circuit name
        holder.circuitName.setText(grandPrix.getCircuitName());
        // Set the location name
        holder.location.setText(grandPrix.getLocalityName() + ", " + grandPrix.getCountryName());
        // Set the country flag
        if (grandPrix.getCountryFlag() == null) {
            holder.countryFlag.setImageBitmap(null);
            if (!grandPrix.isDownloadingImage() && scrollState == SCROLL_STATE_IDLE) {
                DownloadCountryFlagTask imageTask = new DownloadCountryFlagTask(position, grandPrix, holder);
                Utils.executeDownLoadImageTask(imageTask, grandPrix.getCountryFlagUrl());
            }
        } else {
            holder.countryFlag.setImageBitmap(grandPrix.getCountryFlag());
        }
        // Set the row click listener
        convertView.setOnClickListener(new OnItemClickListener(position));
        // Set the row background
        if (position % 2 == 1) {
            convertView.setBackgroundResource(R.drawable.list_row_odd_backgroud);
        } else {
            convertView.setBackgroundResource(R.drawable.list_row_even_backgroud);
        }
        return convertView;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        this.scrollState = scrollState;
        if (scrollState == SCROLL_STATE_IDLE) {
            view.invalidateViews();
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        // Method implemented just because forced by interface
    }

    private class OnItemClickListener implements View.OnClickListener {
        /**
         * The index of the clicked row
         */
        private int position;

        public OnItemClickListener(int position) {
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            delegate.rowClicked(position);
        }
    }


    private class DownloadCountryFlagTask extends AsyncTask<String, Void, Bitmap> {
        private ViewHolder viewHolder;
        private GrandPrix grandPrix;
        private int position;


        private DownloadCountryFlagTask(int position, GrandPrix grandPrix, ViewHolder viewHolder) {
            this.position = position;
            this.grandPrix = grandPrix;
            this.viewHolder = viewHolder;
            grandPrix.setDownloadingImage(true);
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            return Utils.downloadImage(params[0]);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            if (bitmap != null) {
                grandPrix.setCountryFlag(bitmap);
                if (viewHolder.position == position && scrollState == SCROLL_STATE_IDLE) {
                    viewHolder.countryFlag.setImageBitmap(grandPrix.getCountryFlag());
                }
            }
        }
    }

    private class ViewHolder {
        public ImageView countryFlag;
        public TextView raceName;
        public TextView circuitName;
        public TextView location;
        public int position;
    }
}
